package com.example.unique.ui.gallery

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.Spinner
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.unique.R
import com.example.unique.database.DatabaseJob
import com.example.unique.databinding.FragmentGalleryBinding
import androidx.navigation.fragment.findNavController
import androidx.lifecycle.Observer
class GalleryFragment : Fragment() {

    private var _binding: FragmentGalleryBinding? = null
    private val binding get() = _binding!!
    private lateinit var club: String
    private lateinit var galleryViewModel: GalleryViewModel
    private lateinit var jobDatabase:DatabaseJob
    private lateinit var jobStatus: Spinner
    private var status: Int = 0
    private lateinit var jobAdapter: JobAdapter
    //1
    private var isNavigating = false
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        club = activity?.intent?.getStringExtra("club").toString()
        jobDatabase=DatabaseJob.getInstance(requireContext())
        galleryViewModel = GalleryViewModel(jobDatabase)
    }
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentGalleryBinding.inflate(inflater, container, false)
        val root: View = binding.root
        jobAdapter = JobAdapter { taskName ->
            navigateToFragmentContact(taskName) // 跳转到 FragmentA
        }


        binding.recyclerView.layoutManager=LinearLayoutManager(requireContext())
        binding.recyclerView.adapter=jobAdapter
        return root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        jobStatus = binding.searchTargetStatusJob

        // Spinner 状态选择监听器
        jobStatus.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) {
                val selectedText = jobStatus.selectedItem.toString()

                // 默认显示全部状态时加载所有任务
                if (selectedText == "全部状态") {
                    galleryViewModel.getJobsByClub(club) // 加载所有状态的任务
                } else {
                    // 根据状态筛选任务
                    status = getStatus(selectedText)
                    galleryViewModel.getJobsByClubAndStatus(club, status)
                }
            }

            override fun onNothingSelected(parent: AdapterView<*>) {
                // 如果未选择任何状态，默认加载全部任务
                galleryViewModel.getJobsByClub(club)
            }
        }
        // 观察 ViewModel 的 jobList 数据
        galleryViewModel.jobList.observe(viewLifecycleOwner) { jobs ->
            jobAdapter.submitList(jobs) // 更新适配器数据
        }

        // 初始化数据
        galleryViewModel.getJobsByClub(club)
        galleryViewModel.monitorJobStatus(club) // 开始监控任务状态变化


        galleryViewModel.jobList.observe(viewLifecycleOwner) { jobs ->
            jobAdapter.submitList(jobs)
            Log.d("GalleryFragment", "加载任务数量: ${jobs.size}") // 日志
        }


        try {
            // 初始化数据
            galleryViewModel.getJobsByClub(club)
            galleryViewModel.monitorJobStatus(club) // 开始监控任务状态变化
        } catch (e: Exception) {
            Log.e("GalleryFragment", "初始化任务时出错", e)
        }

    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    // 将任务状态文本转换为对应的整数值
    private fun getStatus(text: String): Int = when (text) {
        "进行中" -> 1
        "已完成" -> 2
        "已过期" -> 3
        else -> 0
    }

//    private fun navigateToFragmentContact(taskName: String) {
//        val bundle = Bundle().apply {
//            putString("taskName", taskName) // 将任务名称存储到 Bundle
//        }
//        findNavController().navigate(R.id.action_nav_gallery_to_action_contact, bundle)
//    }



    private fun navigateToFragmentContact(taskName: String) {
        if (isNavigating) return // 防止重复导航
        try {
            val bundle = Bundle().apply {
                putString("taskName", taskName)
            }
            if (findNavController().currentDestination?.id == R.id.nav_gallery) {
                isNavigating = true
                findNavController().navigate(R.id.action_nav_gallery_to_action_contact, bundle)
            }
        } catch (e: Exception) {
            Log.e("GalleryFragment", "导航时出错: ${e.message}", e)
        } finally {
            isNavigating = false
        }

//        val currentDestinationId = findNavController().currentDestination?.id
//        if (currentDestinationId != null) {
//            val destinationName = try {
//                resources.getResourceEntryName(currentDestinationId)
//            } catch (e: Exception) {
//                "未知目标 (ID: $currentDestinationId)"
//            }
//            Log.d("GalleryFragment", "当前目标: $destinationName")
//        } else {
//            Log.d("GalleryFragment", "当前目标为空，无法获取导航状态")
//        }
    }



}
